package com.iwhalecloud.bss.kite.cucc.service.attr.linkhandler;

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.annotation.Resource;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.enums.TriggerStrategy;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.service.attr.handler.LocalInstallAddressAttrHandler;
import com.iwhalecloud.bss.kite.cucc.service.attr.handler.MultipleChargeAttrHandler;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.listener.handler.attr.annotation.AttrHandler;
import com.iwhalecloud.bss.kite.listener.handler.attr.impl.AbstractAttrLinkageHandler;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttrValue;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.ztesoft.bss.base.util.LocalAttrUtils;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;

/**
 * @Classname LocalInstallAddressAttrLinkHandler
 * @Description 获取 省市县 组合组件的值，逗号分隔的字符串，分隔后回填到 省、市、县 对应的各个属性中去
 * @Author zhang.song
 * @Date 2021-03-02 14:53
 */
@Service
@AttrHandler(LocalInstallAddressAttrHandler.class)
public class LocalInstallAddressAttrLinkHandler extends AbstractAttrLinkageHandler<AttrData> {

    @Resource
    private OperateInstAttrService operateInstAttrService;

    @Autowired
    private IOperateSceneCommonService operateSceneCommonService;

    @Resource
    private IQuerySceneInstService querySceneInstService;

    @Override
    public void handle(KiteAttr attr, KiteInst inst, AttrData data) {
        IOperateSceneInstService operateSceneInstService = SpringUtil.getBean(IOperateSceneInstService.class);
        String[] areaFieldName = new String[3];
        String filedName = attr.getFieldName();
        if(KiteStringUtils.equalsAny(filedName, "kit0000225", "2_0000209", "2_0000211", "200001615")) {
            // A端
            areaFieldName[0] = "2_0000220";
            areaFieldName[1] = "2_0000221";
            areaFieldName[2] = "2_0000222";
        } else if(KiteStringUtils.equalsAny(filedName, "kit0000224", "2_0000105","2_0000117")) {
            // Z端
            areaFieldName[0] = "2_0000107";
            areaFieldName[1] = "2_0000109";
            areaFieldName[2] = "2_0000111";
        }

        if(areaFieldName[0] != null) {
            String value = attr.getValue();
            if(KiteStringUtils.isNotEmpty(value)) {
                String[] arr = value.split(",", 3);
                KiteAttr tempAttr;
                for (int i = 0; i < arr.length; i++) {
                    tempAttr = inst.getAttr(areaFieldName[i]);
                    if (Objects.nonNull(tempAttr) && !KiteStringUtils.isEqual(tempAttr.getValue(), arr[i])) {
                        operateInstAttrService.setAttrValue(inst, areaFieldName[i], arr[i], data.getSceneInstId(), null);
                    }
                }
            }
        }

        if(KiteStringUtils.isNotEmpty(attr.getValueDesc())) {
            // 互联网专线 IP地址备案信息模块中 单位所在省 单位所在市 单位所在区 单位详细地址   与装机地址联动
            String[] unitFieldName = new String[3];
            unitFieldName[0] = "2_0000220";
            unitFieldName[1] = "2_0000221";
            unitFieldName[2] = "2_0000222";
            String[] valueArr = attr.getValueDesc().split("-", 3);
            KiteAttr unitTempAttr;
            for (int i = 0; i < valueArr.length; i++) {
                if("200001752".equals(filedName) || "2_0000208".equals(filedName)){
                    unitTempAttr = inst.getAttr(unitFieldName[i]);
                    if (Objects.nonNull(unitTempAttr)) {
                        unitTempAttr.setValue(valueArr[i]);
                        unitTempAttr.setValueDesc(valueArr[i]);
                        operateInstAttrService.setAttrValue(inst, unitFieldName[i], valueArr[i], data.getSceneInstId(), null);
                    }
                }else {
                    unitTempAttr = querySceneInstService.getCommonAttr(data.getSceneInstId(),unitFieldName[i]);
                    if (Objects.nonNull(unitTempAttr)) {
                        unitTempAttr.setValue(valueArr[i]);
                        unitTempAttr.setValueDesc(valueArr[i]);
                        operateSceneCommonService.setCommonAttr(data.getSceneInstId(), unitTempAttr);
                    }
                }
            }
        }
        String provinceStr = DcPublicCache.getPCode("2021092801","PROVINCE_TYPE");
        if (KiteStringUtils.equalsAny(attr.getFieldName(),"2_0000209","2_0000105") && KiteStringUtils.isNotEmpty(provinceStr)) {
            if (KiteStringUtils.isNotEmpty(attr.getValue())) {

                String[] valueArr = attr.getValue().split(SymbolConsts.COMMA);
                KiteAttr addressDetial = null;
                if (KiteStringUtils.equals(attr.getFieldName(),"2_0000209")) {
                    addressDetial = inst.getAttr("2_0000211");
                } else if (KiteStringUtils.equals(attr.getFieldName(),"2_0000105")) {
                    addressDetial = inst.getAttr("2_0000117");
                }
                if (Objects.nonNull(addressDetial)) {
                    if (valueArr.length>0 && KiteStringUtils.equalsAny(valueArr[0],provinceStr.split(SymbolConsts.COMMA))) {
                        addressDetial.setIsEdit("SF");
                    } else {

                        String provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
                        DcPublic mapAidConfig = DcPublicCache.getByPcode("2202241001", "MAP_AID_QRY_BTN", inst.getSpecId()).stream().findFirst().orElse(null);

                        if (Objects.nonNull(mapAidConfig)) {
                            String provConfig = mapAidConfig.getCodea();
                            if ((provConfig.contains(provinceCode) || KiteStringUtils.equals(provConfig, "-1"))) {
                                attr.setIsEdit("SF");
                            }
                            else {
                                addressDetial.setIsEdit(KeyConsts.IFTRUE_T);
                            }
                        }
                        else {
                            addressDetial.setIsEdit(KeyConsts.IFTRUE_T);
                        }
                    }
                    operateSceneInstService.setAttr(data.getSceneInstId(), inst.getInstType(), inst.getInstId(), addressDetial);
                }
            }
        }
//跨域优化联动要求完成时间
//        if (data.getServiceOfferId().equals(LocalServiceOfferConsts.SERVICE_OFFER_RESOURCE_CHECK) && !ServiceContext.getIsBatchAccept()) {
//            String nodeCode = querySceneInstService.getExtParameterValue(data.getSceneInstId(), "nodeCode");
//            if (null == nodeCode) {
//                nodeCode = MapUtils.getString(ContextUtil.getLoginInfo().getUserInfo().getExtParams(), "nodeCode");
//            }
//            if (KiteStringUtils.equalsAny(attr.getFieldName(), "2_0000209", "2_0000105") && KiteStringUtils.isNotEmpty(provinceStr)) {
//                String[] valueArr = attr.getValue().split(SymbolConsts.COMMA);
//                if (null != valueArr[0]) {
//                    KiteAttr finishTime = null;
//                    if (KiteStringUtils.equals(attr.getFieldName(), "2_0000209")) {
//                        finishTime=querySceneInstService.getCommonAttr(data.getSceneInstId(), "2_0000122");                        //Z端要求完成时间
//                    } else if (KiteStringUtils.equals(attr.getFieldName(), "2_0000105")) {
//                        finishTime=querySceneInstService.getCommonAttr(data.getSceneInstId(), "2_0000123");                    }
//                    if (Objects.nonNull(finishTime)) {
//                        String value = finishTime.getValue();
//
//                        //核查重提
//                        String productId = inst.getSpecId();
//                        if ("OrderResubmit".equals(nodeCode)) {
//                            value = LocalAttrUtils.compareDate(finishTime, inst.getSpecId(), valueArr[0]);
//                            finishTime.setDefaultValue(value);
//                        } else {
//                            value = LocalAttrUtils.getInstance().AZOffsetDay(productId, null, valueArr[0]);
//                            finishTime.setDefaultValue(value);
//                        }
//
//                        finishTime.setValue(value);
//                        finishTime.setValueDesc(value);
//                        //        核查追单追单校验
//                        String BIZ_TYPE = MapUtils.getString(this.querySceneInstService.getExtParameter(data.getSceneInstId()), "serviceOfferId");
//                        if (KiteStringUtils.equals(LocalServiceOfferConsts.SERVICE_OFFER_FOLLOW, BIZ_TYPE) && "OrderResourceCheck".equals(nodeCode)) {
//                            finishTime.setValue(LocalAttrUtils.compareDate(finishTime, inst.getSpecId(), valueArr[0]));
//                            finishTime.setDefaultValue(LocalAttrUtils.compareDate(finishTime, inst.getSpecId(), valueArr[0]));
//                            finishTime.setValueDesc(LocalAttrUtils.compareDate(finishTime, inst.getSpecId(), valueArr[0]));
//                        }
//
//                        operateSceneCommonService.setCommonAttr(data.getSceneInstId(), finishTime);                    }
//                }
//            }
//        }
        //        处理pop点

        KiteAttr popAttr = null;
        if(KiteStringUtils.equalsAny(filedName, "kit0000225", "2_0000209", "2_0000211", "200001615")) {
            // A端
             popAttr = inst.getAttr("210004649");
        } else if(KiteStringUtils.equalsAny(filedName, "kit0000224", "2_0000105","2_0000117")) {
            // Z端
             popAttr = inst.getAttr("210004650");
        }
        if (null != attr.getValue() && Objects.nonNull(popAttr)) {
            String[] arr = attr.getValue().split(",", 3);
            if (arr.length > 1) {
                List<JSONObject> pops = LocalAttrUtils.getInstance().qryPopData(arr[1]);
                    List<KiteAttrValue> attrValues = new ArrayList<>();
                if (null != pops && pops.size() > 0) {
                    KiteAttrValue kiteAttrValue0 = new KiteAttrValue();
                    kiteAttrValue0.setAttrValue("");
                    kiteAttrValue0.setAttrId("202110151406");
                    kiteAttrValue0.setAttrValueName("--请选择--");
                    kiteAttrValue0.setSortBy("0");
                    attrValues.add(kiteAttrValue0);
                    for (JSONObject o : pops) {
                        KiteAttrValue attrValue = new KiteAttrValue();
                        attrValue.setAttrId(kiteAttrValue0.getAttrId());
                        attrValue.setAttrValue(o.getString("STATION_CODE"));
                        attrValue.setAttrValueName(o.getString("STATION_NAME"));
                        attrValues.add(attrValue);
                    }
                    popAttr.setAttrValues(attrValues);
                    operateSceneInstService.setAttr(data.getSceneInstId(), inst.getInstType(), inst.getInstId(), popAttr);
                }else{
                    popAttr.setAttrValues(attrValues);
                    operateSceneInstService.setAttr(data.getSceneInstId(), inst.getInstType(), inst.getInstId(), popAttr);
                }
            }
        }
        if (!TriggerStrategy.LOAD_VALUE.equals(data.getTriggerStrategy())) {
            linkClearValue(attr,inst,data);
         // 处理局端机房
            KiteAttr machineRoomeAttr = inst.getAttr("2_0000162");
            if(Objects.nonNull(machineRoomeAttr) && KiteStringUtils.isEqual(attr.getFieldName(), "2_0000105")) {
                String cityValue = attr.getValueDesc();
                if (KiteStringUtils.isNotEmpty(cityValue)) {
                    String[] cityArray = cityValue.split(SymbolConsts.HYPHEN);
                    StringBuffer machineRoomValue = new StringBuffer(cityArray[0]).append("省");
                    if (cityArray.length>=2) {
                        machineRoomValue.append(cityArray[1]).append("市");
                    }
                    machineRoomValue.append("PE机房");
                    operateInstAttrService.setAttrValue(inst, "2_0000162", machineRoomValue.toString(), data.getSceneInstId(), null);
                }
            }
        }
        // 云联网专线接入产品-新版   接入节点名称：接入地址+当前受理时间的时分秒
        if("10003509".equals(inst.getSpecId()) && KiteStringUtils.equalsAny(data.getServiceOfferId(), ServiceOfferConsts.SERVICE_OFFER_ORDER)){
            String accseeNodeName = attr.getValueDesc().replace("-", "");
            accseeNodeName += LocalTime.now().format(DateTimeFormatter.ofPattern("HHmmss"));
            operateInstAttrService.setAttrValue(inst, "200001915", accseeNodeName, data.getSceneInstId(), null);
        }

        // 是否多方收费，非跨域不可修改，选择装机地址后进行判断
        KiteAttr isMultipleChargeAttr = inst.getAttr("210008004");
        if(Objects.nonNull(isMultipleChargeAttr)) {
            MultipleChargeAttrHandler multipleChargeAttrHandler = SpringUtil.getBean(MultipleChargeAttrHandler.class);
            multipleChargeAttrHandler.setMultipleChargeAttr(isMultipleChargeAttr, inst, data.getSceneInstId(), null);
        }
    }

    @Override
    public void handleStyle(KiteAttr attr, KiteInst inst, AttrData data) {

    }

    /**
     * 在产商品属性页面，如果修改了装机地址省市区县的任一信息，则需要将装机地址、标准地址ID、楼宇编码、楼宇名称信息清空
     */
    private void linkClearValue(KiteAttr attr, KiteInst inst, AttrData data){
        KiteAttr aAddressAttr = inst.getAttr("2_0000209");
        KiteAttr zAddressAttr = inst.getAttr("2_0000105");

        if (KiteStringUtils.equals(attr.getFieldName(),"2_0000209") && Objects.nonNull(aAddressAttr) && !KiteStringUtils.equals(aAddressAttr.getValue(),aAddressAttr.getOriginValue())){
            //装机地址、A端装机地址
            KiteAttr installAddrAttr = inst.getAttr("2_0000211");
            if (Objects.nonNull(installAddrAttr) && KiteStringUtils.isNotEmpty(installAddrAttr.getValue())
                && (!installAddrAttr.getValue().startsWith("{") || !installAddrAttr.getValue().endsWith("}"))){
                this.removeAttrValue("2_0000211", inst, data);
                this.removeAttrValue("200002618", inst, data);
                this.removeAttrValue("200001951", inst, data);
                this.removeAttrValue("210003991", inst, data);
                this.removeAttrValue("200002737", inst, data);
                this.removeAttrValue("200002982", inst, data);
            }
        } else if (KiteStringUtils.equals(attr.getFieldName(),"2_0000105") && Objects.nonNull(zAddressAttr) && !KiteStringUtils.equals(zAddressAttr.getValue(),zAddressAttr.getOriginValue())){
            //Z端装机地址
            KiteAttr installAddressAttr = inst.getAttr("2_0000117");
            if (Objects.nonNull(installAddressAttr) && KiteStringUtils.isNotEmpty(installAddressAttr.getValue())
                && (!installAddressAttr.getValue().startsWith("{") || !installAddressAttr.getValue().endsWith("}"))){
                this.removeAttrValue("2_0000117", inst, data);
                this.removeAttrValue("200002619", inst, data);
                this.removeAttrValue("210003992", inst, data);
                this.removeAttrValue("200002985", inst, data);
            }
        }
    }

    private void removeAttrValue(String fieldName, KiteInst inst, AttrData data) {
        KiteAttr attr = inst.getAttr(fieldName);
        if (Objects.nonNull(attr) && KiteStringUtils.isNotEmpty(attr.getValue())){
            operateInstAttrService.setAttrValue(inst, attr.getFieldName(),"", data.getSceneInstId(),null);
        }
    }
}
